package cn.jdemo.cron.hashedWheelTimer;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;

import java.util.concurrent.*;

/**
 * 1) HashedWheelTimer 对应一个线程
 * 2) 大批量的调度任务，都绑定到同一个的调度器上面
 * 3) 可以用线程池处理任务
 * 4) 可以在(一个线程)/HashedWheelTimer中，动态的添加/删除定时(延时)任务
 *
 * @see HashedWheelTimer#HashedWheelTimer(ThreadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection, long maxPendingTimeouts, Executor taskExecutor)
 * tickDuration 每一tick的时间
 * ticksPerWheel 即多少个tick才能走完这个wheel一圈
 *
 */
public class Demo01 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    private static void test02() throws InterruptedException {
        HashedWheelTimer timer = new HashedWheelTimer(Executors.defaultThreadFactory(),1, TimeUnit.SECONDS, 10,
                true,-1, Executors.newFixedThreadPool(10));
        Timeout tim = timer.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                System.out.println(timeout);
            }
        }, 2, TimeUnit.SECONDS);

        timer.start();

        Thread.sleep(6000);
        timer.stop();
    }

    private static void test01() throws InterruptedException {
        HashedWheelTimer timer = new HashedWheelTimer(1, TimeUnit.SECONDS, 10);
        Timeout tim = timer.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                System.out.println(timeout);
            }
        }, 2, TimeUnit.SECONDS);

        Timeout tim1 = timer.newTimeout((TimerTask) timeout -> {
            System.out.println("任务2执行");
            System.out.println("线程名称:" + Thread.currentThread().getName());
        }, 5, TimeUnit.SECONDS);

        timer.start();

        Thread.sleep(6000);
        timer.stop();
    }
}
